/**
 * date:2020/03/01
 * author:wujian
 * version:2.0
 * description:layuimini 统一访问接口
 */
layui.define(['form','dropdown','xmSelect','myUtil','myApi'],function (exports) {
    var $ = layui.jquery;
    var dropdown = layui.dropdown;
    var xmSelect = layui.xmSelect;
    var table = layui.table;
    var form = layui.form;
    var myUtil = layui.myUtil;
    var myApi = layui.myApi;
    var myComp = {

        // 默认选择框
        defaultTable : function (config) {
            var defaultConfig = {
                // elem: elem,
                even: true,
                // url: url, // 此处为静态模拟数据，实际使用时需换成真实接口
                // toolbar: toolbar,
                defaultToolbar: ['filter', 'exports', 'print'],
                height: 'full-90', // 最大高度减去其他容器已占有的高度差
                css: [ '.layui-table-tool-temp{padding-right: 145px;}'].join(''), // 重设当前表格样式
                cellMinWidth: 80,
                totalRow: false, // 开启合计行
                page: true,
                limit: 12,
                limits: [12,15,20,30,50,100,500,1000,2000,10000],
                method:'post',
                contentType:'application/json',
                request:{
                    pageName: 'pageNum', //页码的参数名称，默认：page
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                },
                parseData:function(res){
                    return {"code":0, "msg":"", "count":res.data.total, "data":res.data.list }
                },
                // cols: cols,
                done: function () { },
                error: function (res, msg) {
                    console.log(res, msg)
                }
            }
            defaultConfig = Object.assign(defaultConfig, config)
            return table.render(defaultConfig);
        },

        // 默认选择框
        defaultxmSelect : function (config) {
            var defaultConfig = {
                radio: true,
                clickClose:true,
            }
            defaultConfig = Object.assign(defaultConfig, config)
            return xmSelect.render(defaultConfig);
        },

        // 默认弹出框
        defaultLayer : function (title,content,confirmFn){
            layer.open({
                title: title,
                type: 1,
                area: ['60%', '80%'],
                content: content,
                btn: ['确定', '取消'],
                yes: confirmFn,
                success: function(layero, index, that){
                    // layero.appendTo($('.layui-layer-shade').parent()); // 将弹出框架加到遮盖层,否则会被遮挡
                    $('.layui-layer-shade').appendTo(layero.parent())
                    layer.setTop(layero); // 重点 2 --- 保持选中窗口置顶

                    // 记录索引，以便按 esc 键关闭。事件见代码最末尾处。
                    layer.escIndex = layer.escIndex || [];
                    layer.escIndex.unshift(index);
                    // 选中当前层时，将当前层索引放置在首位
                    layero.on('mousedown', function(){
                        var _index = layer.escIndex.indexOf(index);
                        if(_index !== -1){
                            layer.escIndex.splice(_index, 1); //删除原有索引
                        }
                        layer.escIndex.unshift(index); //将索引插入到数组首位
                    });

                    // 添加form标识
                    layero.addClass('layui-form');
                    // 将保存按钮改变成提交按钮
                    layero.find('.layui-layer-btn0').attr({
                        'lay-filter': 'default-layer-form-submit',
                        'lay-submit': ''
                    });
                    form.render();
                },
                end: function(){
                    //更新索引
                    console.log('end.................')
                    if(typeof layer.escIndex === 'object'){
                        layer.escIndex.splice(0, 1);
                    }
                },

            });
        },

        //默认右侧固定列监听事件
        defaultTableToolEvent : function (node, pageObj, tableLayId, toolEventFn) {
            tableLayId = (tableLayId ? tableLayId : 'default-table');
            //右侧固定列监听事件
            if (!toolEventFn) {
                toolEventFn = function (obj) {
                    if (obj.event === 'edit') {
                        myComp.defaultUpdateBtnEvent(node,pageObj,obj.data)
                        // node.operate(obj,'update');
                    } else if (obj.event === 'more') {
                        dropdown.render({elem: this,show: true,
                            data: [{ title: '查看', id: 'detail' },{ title: '删除', id: 'del' }],
                            click: function (menudata) {
                                if (menudata.id === 'detail') {myComp.defaultUpdateBtnEvent(node,pageObj,obj.data)}
                                else if (menudata.id === 'del') {myComp.defaultDeleteBtnEvent(node,pageObj,true,obj.data)}
                            },
                            align: 'right', // 右对齐弹出
                            style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                        })
                    }
                };
            }
            var toolVar = 'tool('+tableLayId+')';
            table.on(toolVar, toolEventFn);
        },

        // 默认搜索按钮
        defaultSearchBtnEvent : function (node,pageObj, queryFormLayId, tableLayId, btnId) {
            // 初始化
            queryFormLayId = (queryFormLayId ? queryFormLayId : 'default-search-form');
            tableLayId = (tableLayId ? tableLayId : 'default-table');
            btnId = (btnId ? btnId : '#default-search-btn');
            // 设置事件
            $(btnId).on('click', function () {
                console.log('search............');
                myComp.defaultQueryFn(queryFormLayId,tableLayId);
            });
        },

        defaultQueryFn : function (queryFormLayId,tableLayId) {
            queryFormLayId = (queryFormLayId ? queryFormLayId : 'default-search-form');
            var formData = layui.form.val(queryFormLayId);
            table.reloadData(tableLayId, {
                page: {curr: 1},
                where: formData,
                scrollPos: true
            });
        },

        // 自定义校验
        defaultVerify : function (pageObj, myData) {
            // 自定义定校验
            if (pageObj.verifyDataFn) {
                var verifyDataArr = pageObj.verifyDataFn(myData)
                if (verifyDataArr && verifyDataArr.length > 0) {
                    layer.msg(verifyDataArr[0].text, {icon: 0}, function(){ });
                    return false
                }
            }
            return true
        },

        // 默认新增按钮
        defaultAddBtnEvent : function (node, pageObj, data, operateFormLayId, queryFormLayId, tableLayId, btnId) {
            // 初始化
            operateFormLayId = (operateFormLayId ? operateFormLayId : 'default-layer-form');
            tableLayId = (tableLayId ? tableLayId : 'default-table');
            btnId = (btnId ? btnId : '#default-add-btn');

            // 执行
            $(btnId).on('click', function () {
                // 设置数据
                myUtil.resetForm('#'+operateFormLayId);
                if (pageObj && pageObj.initFormDataFn) {
                    pageObj.initFormDataFn(operateFormLayId)
                }
                // 弹框
                myComp.defaultLayer('新增数据',$('#'+operateFormLayId), function (index, layero) {
                    console.log('submit222.....')

                    form.on('submit(default-layer-form-submit)', function () {
                        console.log('submit.....')
                        var myData = layui.form.val(operateFormLayId);
                        if (pageObj && pageObj.formToDataFn) {
                            myData = pageObj.formToDataFn(myData);
                        }
                        // 自定义定校验
                        if (!myComp.defaultVerify(pageObj, myData)) {
                            return
                        }
                        myData.operateType=1;
                        myApi.postJson(pageObj.operateUrl,[myData], function (res) {
                            layer.msg("操作成功！");
                            layer.close(index);
                            myComp.defaultQueryFn(queryFormLayId,tableLayId);
                        })
                    })
                    return false;
                });
            });
        },

        // 默认修改按钮
        defaultUpdateBtnEvent : function (node,pageObj, data, operateFormLayId, queryFormLayId, tableLayId) {
            // 初始化
            operateFormLayId = (operateFormLayId ? operateFormLayId : 'default-layer-form');
            tableLayId = (tableLayId ? tableLayId : 'default-table');
            // 设置数据
            myUtil.resetForm('#'+operateFormLayId);
            // 执行
            // var checkStatus = table.checkStatus(tableLayId)
            // var data = checkStatus.data;
            if(!data ||　data.length==0 || data.length > 1){
                layer.alert(((data.length>1)?"只能选择一条数据。":"请先选择一条数据。"));
                return;
            }
            //给表单赋值
            var tmpData = data
            if (pageObj && pageObj.dataToFormFn) {
                tmpData = pageObj.dataToFormFn(data)
            }
            layui.form.val(operateFormLayId, tmpData);

            // 弹框
            myComp.defaultLayer('修改数据',$('#'+operateFormLayId), function (index, layero) {
                form.on('submit(default-layer-form-submit)', function () {
                    var myData = layui.form.val(operateFormLayId);
                    if (pageObj && pageObj.formToDataFn) {
                        myData = pageObj.formToDataFn(myData);
                    }
                    // 自定义定校验
                    if (!myComp.defaultVerify(pageObj, myData)) {
                        return
                    }
                    myData.operateType=2;
                    myApi.postJson(pageObj.operateUrl,[myData], function (res) {
                        layer.msg("操作成功！");
                        layer.close(index);
                        myComp.defaultQueryFn(queryFormLayId,tableLayId);
                    })
                })
                return false;
            });
        },

        // 默认删除按钮
        defaultDeleteBtnEvent : function (node, pageObj, promte, data, queryFormLayId, tableLayId, btnId) {
            // 初始化
            tableLayId = (tableLayId ? tableLayId : 'default-table');
            btnId = (btnId ? btnId : '#default-delete-btn');
            // 设置批量删除事件
            if (!promte) {
                $(btnId).on('click', function () {
                    console.log('del............');
                    var checkStatus = table.checkStatus(tableLayId)
                    var data = checkStatus.data;
                    if(!data ||　data.length==0){
                        layer.alert("请先选择数据。");
                        return;
                    }
                    var msg = ''
                    for (var i = 0; i < data.length; i++) {
                        msg += (i==data.length-1)? data[i].id :(data[i].id+',')
                    }
                    layer.confirm('真的删除行 [id: ' + msg + '] 么', function (index) {
                        var myData = data;
                        if (pageObj && pageObj.formToDataFn) {
                            myData = pageObj.formToDataFn(data);
                        }
                        for (var i = 0; i < myData.length; i++) {
                            myData[i].operateType=3;
                        }
                        myApi.postJson(pageObj.operateUrl, myData, function (res) {
                            layer.msg("操作成功！");
                            layer.close(index);
                            myComp.defaultQueryFn(queryFormLayId,tableLayId);
                        })
                        return false;
                    });
                });
            // 固定列删除事件,直接弹框
            } else {
                console.log('del............');
                // var checkStatus = table.checkStatus(tableLayId)
                // var data = checkStatus.data;
                if(!data ||　data.length==0){
                    layer.alert("请先选择数据。");
                    return;
                }

                layer.confirm('真的删除行 [id: ' + data.id + '] 么', function (index) {
                    var myData = data;
                    if (pageObj && pageObj.formToDataFn) {
                        myData = pageObj.formToDataFn(data);
                    }
                    myData.operateType=3;
                    myApi.postJson(pageObj.operateUrl,[myData], function (res) {
                        layer.msg("操作成功！");
                        layer.close(index);
                        myComp.defaultQueryFn(queryFormLayId,tableLayId);
                    })
                    return false;
                });
            }
        },

        // 默认基本页面设置
        initPage : function (node,pageObj) {
            pageObj.tableToolEvent ? null : myComp.defaultTableToolEvent(node,pageObj);
            pageObj.searchBtnEvent ? null :myComp.defaultSearchBtnEvent(node,pageObj);
            pageObj.addBtnEvent ? null : myComp.defaultAddBtnEvent(node,pageObj);
            pageObj.deleteBtnEvent ? null : myComp.defaultDeleteBtnEvent(node,pageObj);
        }

    };

    exports("myComp", myComp);
});